package com.common;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.model.Users;
import com.util.HibernateUtils;

public class BaseDAO<T, PK extends Serializable> implements IBaseDAO<T, PK> {
	private Class<T> clazz;

	public BaseDAO() {
		clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
				.getActualTypeArguments()[0];
	}

	public T get(PK id) {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		T t=(T) session.get(clazz, id);
		tx.commit();
		session.close();
		return t;
	}

	public List<T> getAll() {
		return findHql("from " + clazz.getName());
	}

	public void save(T entity) {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		session.save(entity);
		tx.commit();
	}

	public void update(T entity) {
		
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		session.update(entity);
		tx.commit();;
	}

	public void delete(T entity) {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		session.delete(entity);
		tx.commit();;
	}
	public void delete(PK id) {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		session.delete(session.get(clazz, id));
		tx.commit();;
	}

	public List<T> findHql(String hql) {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		List<T> list=session.createQuery(hql).list();
		tx.commit();
		return (List<T>) list;
	}
	public List<T> findSql(String sql) {
		Session session = HibernateUtils.getSession();
		Transaction tx = session.beginTransaction();
		List<T> list=session.createSQLQuery(sql).addEntity(clazz).list();
		tx.commit();
		return (List<T>) list;
	}
}
